package net.itfenxiang.mybatisplus.trans.service.impl;

import com.fhs.trans.service.impl.DictionaryTransService;
import lombok.AllArgsConstructor;
import net.itfenxiang.mybatisplus.trans.dao.SysDictDataMapper;
import net.itfenxiang.mybatisplus.trans.entity.SysDictData;
import net.itfenxiang.mybatisplus.trans.entity.SysDictType;
import net.itfenxiang.mybatisplus.trans.dao.SysDictTypeMapper;
import net.itfenxiang.mybatisplus.trans.service.ISysDictTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典类型 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-04-29
 */
@Service
@AllArgsConstructor
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements ISysDictTypeService, InitializingBean {

    private final SysDictDataMapper sysDictDataDao;
    private final DictionaryTransService dictionaryTransService;

    @Override
    public void afterPropertiesSet() throws Exception {
        refreshTransCache();
    }

    public void refreshTransCache() {
        //异步不阻塞主线程，不会影响启动速度
        CompletableFuture.supplyAsync(() -> {
            //获取所有字典项的数据
            List<SysDictData> sysDictDatas = sysDictDataDao.selectList(null);
            //根据类型分组
            Map<Long, List<SysDictData>> dictTypeDataMap = sysDictDatas.stream()
                    .collect(Collectors.groupingBy(SysDictData::getDictTypeId));
            List<SysDictType> dictTypes = super.list();
            for (SysDictType dictType : dictTypes) {
                if (dictTypeDataMap.containsKey(dictType.getId())) {
                    dictionaryTransService.refreshCache(dictType.getDictType(), dictTypeDataMap.get(dictType.getId())
                            .stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel))
                    );
                }
            }
            return null;
        });
    }
}
